<template>
  <div id="reg">
    <van-form @submit="onSubmit" ref="form">
      <van-field
        v-model.trim="phone"
        name="phone"
        label="手机号"
        maxlength="11"
        placeholder="请输入手机号"
        :rules="[{ required: true, message: '请输入手机号' }]"
      />
      <van-field
        v-model.trim="captcha"
        name="captcha"
        type="number"
        center
        clearable
        maxlength="4"
        label="短信验证码"
        placeholder="请输入四位验证码"
        :rules="[{ required: true, message: '请输入密码' }]"
      >
        <template #button>
          <van-count-down
            @finish="isShow = false"
            v-if="isShow"
            :time="60 * 1000"
            format="ss s"
          />
          <van-button
            v-else
            native-type="button"
            size="small"
            type="default"
            @click="onCode"
            class="codeBtn"
            >发送验证码</van-button
          >
        </template>
      </van-field>
      <van-field
        v-model.trim="password"
        type="password"
        name="password"
        maxlength="16"
        label="密码"
        placeholder="请输入密码"
        :rules="[{ required: true, message: '请输入密码' }]"
      />
      <van-field
        v-model.trim="nickNmae"
        name="nickNmae"
        label="昵称"
        maxlength="6"
        placeholder="请输入昵称"
        :rules="[{ required: true, message: '请输入昵称' }]"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          type="danger"
          color="linear-gradient(to right, #ff6034, #ee0a24)"
          native-type="submit"
          >注册</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { Toast } from 'vant'
import { regPhone, codePhone, phoneRepeat } from '@/api/login'
export default {
  name: 'Reg',
  data () {
    return {
      phone: '',
      captcha: '',
      password: '',
      nickNmae: '',
      isShow: false
    }
  },

  // 定义方法
  methods: {
    async onSubmit (values) {
      try {
        await regPhone(values)
        Toast('注册成功，去登陆！')
        this.$router.push('/login')
      } catch (err) {
        Toast('注册失败，未知的错误！')
      }
    },
    async onCode () {
      const res2 = await phoneRepeat({
        phone: this.phone
      })
      if (res2.exist === 1) {
        Toast('账号存在')
      } else {
        try {
          await this.$refs.form.validate('phone')
        } catch (err) {
          return
        }
        const res = await codePhone({
          phone: this.phone
        })
        console.log(res)
        this.isShow = true
      }
    }
  }
}
</script>

<style scoped lang="less">
.codeBtn {
  border: 1px solid red;
  color: red;
}
</style>
